<?php
/*
 * -------------------------
 * sql
 * -------------------------
*/
//将数组转换成供insert用的字符串
function arr_insert($arr)
{
  foreach ($arr as $k => $v) {
    $tmp_key[] = "`" . $k . "`";
    $tmp_value[] = "'" . str_isafe($v) . "'";
  }
  return "(" . implode(',', $tmp_key) . ") VALUES (" . implode(',', $tmp_value) . ")";
}
//将数组转换成供update用的字符串
function arr_update($arr)
{
  $tmp = '';
  foreach ($arr as $k => $v) {
    $tmp .= "`" . $k . "` = '" . str_isafe($v) . "',";
  }
  return rtrim($tmp, ',');
}
function update_array_str($arr, $str)
{
  if (in_array($str, $arr) !== true) {
    array_push($arr, $str);
  }
  return $arr;
}
function array_pick($haystack, $needle_key = '', $needle_value = '')
{
  if (empty($haystack)) return $haystack;
  $res = array();
  foreach ($haystack as $val) {
    if ($val[$needle_key] == $needle_value) {
      $res[] = $val;
    }
  }
  return $res;
}
function array_order($haystack, $order_key = '', $order_type = 0)
{
  if (empty($haystack)) return $haystack;
  $arr = array_column($haystack, $order_key);
  return array_multisort($arr, $order_type ? 'SORT_DESC' : 'SORT_ASC', $haystack);
}
function array_input($arr, $esc = [])
{
  $str = '';

  foreach ($arr as $key => $value) {
    if (in_array($key, $esc)) continue;
    $str .= '<input type="hidden" name="' . $key . '" value="' . $value . '">';
  }

  return $str;
}

//获取频道字段
function get_channel($t0, $t1 = "")
{
  $t0 = intval($t0);

  if (!empty($t1)) {
    return $GLOBALS['db']->getOne("SELECT $t1 FROM channel WHERE id = '" . $t0 . "'");
  }

  return $GLOBALS['db']->getRow("SELECT * FROM channel WHERE id = '" . $t0 . "'");
}

function list_detail($c_sub, $limit, $order = '')
{
  $order = $order ? $order : 'd_order ASC,id DESC';
  return $GLOBALS['db']->getAll("SELECT * FROM detail WHERE d_parent IN ($c_sub) AND d_enable = 1 ORDER BY $order LIMIT $limit");
}
function list_channel($c_id, $order = '')
{
  $order = $order ? $order : 'c_order ASC,id ASC';
  return $GLOBALS['db']->getAll("SELECT * FROM channel WHERE c_parent = $c_id AND c_navigation = 1 ORDER BY $order");
}
function list_slider($s_parent = '', $order = '')
{
  $order = $order ? $order : 's_order ASC,id ASC';
  $s_parent = $s_parent != '' ? $s_parent : 'global';
  return $GLOBALS['db']->getAll("SELECT * FROM slideshow WHERE s_parent='$s_parent' ORDER BY $order");
}
function list_link($limit = '', $order = '')
{
  $limit = !empty($limit) ? "LIMIT $limit" : '';
  $order = $order ? $order : 'l_order ASC,id ASC';
  return $GLOBALS['db']->getAll("SELECT * FROM link ORDER BY $order $limit");
}

// 获取某表的某值
function get_col($table, $col, $where)
{
  return $GLOBALS['db']->getOne("SELECT $col FROM $table WHERE $where");
}
function get_row($table, $where, $col = '')
{
  return $GLOBALS['db']->getRow("SELECT " . ($col != '' ? $col : "*") . " FROM $table WHERE $where");
}
// 获取碎片内容
function get_chip($var)
{
  $where = is_numeric($var)
    ? "id = '" . intval($var) . "'"
    : "c_code = '" . str_text($var) . "'";

  return $GLOBALS['db']->getOne("SELECT c_content FROM chip WHERE $where");
}

/**
 * nav
 */

//无限级导航(宽屏) 为了默认模板留存已摒弃
function navigation($pid, $pre, $id, $level = 2, $root_class = "navigation am-hide-md-down", $sub_class = "sub")
{
  $tmp = '';
  $pid = intval($pid);
  $id = intval($id);
  $level = intval($level);
  $root_class = str_safe($root_class);
  $sub_class = str_safe($sub_class);

  $root = cms('nav_level_' . $pid) !== NULL ? cms('nav_level_' . $pid) : '';
  if ($root != '') {
    cms('nav_level_' . $pid, $pid);
    $root = $pid;
  }
  if ($level > 0) {
    $res = $GLOBALS['db']->getAll("SELECT * FROM channel WHERE c_navigation = 1 AND c_parent = " . $pid . " ORDER BY c_order ASC , id ASC");
    $level--;
    foreach ($res as $row) {
      $nav_name = !empty($row['c_nname']) ? $row['c_nname'] : $row['c_name'];
      if ($pid == 0) {
        $tmp .= '<li ' . ($row['c_main'] == $id && $id ? 'class="active"' : '') . '><a href="' . c_url($row['id'], $row['c_link']) . '" target="' . $row['c_target'] . '">' . $nav_name . '</a>' . navigation($row['id'], '', $id, $level) . '</li>';
      } else {
        $tmp .= '<li ' . ($row['id'] == $id ? 'class="active"' : '') . '><a href="' . c_url($row['id'], $row['c_link']) . '" target="' . $row['c_target'] . '">' . $nav_name . '</a>' . navigation($row['id'], '', $id, $level) . '</li>';
      }
    }
  }
  if (!empty($tmp)) {
    return '<ul class="' . ($pid == $root ? $root_class : $sub_class) . '">' . $pre . $tmp . '</ul>';
  }
}

function nav_m($pid = 0, $sid = 0, $level = 3)
{
  $html = '';

  if ($level > 0) {

    $cat = $GLOBALS['db']->getAll("SELECT * FROM channel WHERE c_navigation = 1 AND c_parent = '" . $pid . "' ORDER BY c_order ASC , id ASC");
    $level--;

    foreach ($cat as $row) {
      $nav_name = !empty($row['c_nname']) ? $row['c_nname'] : $row['c_name'];
      if ($row['c_ifsub'] == 1 && $level > 0) {
        $html .= '<li class="dropdown"><a href="' . c_url($row['id'], $row['c_link']) . '" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="false" aria-expanded="false">' . $nav_name .  '<span class="caret"></span></a><ul class="dropdown-menu">' . nav_m($row['id'], $sid, $level) . '</ul></li>';
      } else {
        $html .= '<li class="' . ($sid == $row['id'] ? 'active' : '') . '"><a href="' . c_url($row['id'], $row['c_link']) . '">' . $nav_name . '</a>' . nav_m($row['id'], $sid, $level) . '</li>';
      }
    }

    return $html;
  }
}

//无限级导航（移动端)
// $s[mainul|subul|liclass|liactive|lidata|aclass|adata|icondown]
// $s[0     |1    |2      |3       |4     |5     |6    |7]
function navigation_m($pid, $pre, $id, $level = 3, $ext = '')
{
  $tmp = '';
  $pid = intval($pid);
  $id = intval($id);
  $level = intval($level);

  if ($level > 0) {
    $res = $GLOBALS['db']->getAll("SELECT * FROM channel WHERE c_navigation = 1 AND c_parent = '" . $pid . "' ORDER BY c_order ASC , id ASC");
    $level--;
    foreach ($res as $row) {
      $nav_name = !empty($row['c_nname']) ? $row['c_nname'] : $row['c_name'];

      if ($row['c_ifsub'] == 1 && $level > 0) {
        $tmp .= '<li class="dropdown ' . ($row['c_main'] == $id && $id ? 'active' : '') . '"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">' . $nav_name .  '<span class="caret"></span></a><ul class="dropdown-menu">' . navigation_m($row['id'], '', $id, $level, '') . '</ul></li>';
      } else {
        $tmp .= '<li class="' . ($row['id'] == $id ? 'active' : '') . '"><a href="' . c_url($row['id'], $row['c_link']) . '">' . $nav_name . '</a>' . navigation_m($row['id'], '', $id, $level, '') . '</li>';
      }
    }
    return $pre . $tmp . $ext;
  }
}

//频道列表
function channel_slist($pid, $id, $level = 2)
{
  $pid = intval($pid);
  $id = intval($id);
  $level = intval($level);

  if ($id > 0) {
    $tmp = '';
    $res = $GLOBALS['db']->getAll("SELECT * FROM channel WHERE c_parent = '" . $pid . "' AND c_navigation=1 ORDER BY c_order ASC , id ASC ");
    foreach ($res as $row) {
      $tmp .= '<li ' . ($row['id'] == $id ? ' class="active"' : '') . '><a href="' . c_url($row['id'], $row['c_link']) . '" target="' . $row['c_target'] . '">' . $row['c_name'] . '</a></li>';
    }
  }

  $level--;

  return $level == 2 ? $tmp : '<ul>' . $tmp . '</ul>';
}

//频道和内容页的当前位置
function current_channel_location($pid, $sid, $code = '<li class="am-active"><a href="|</a></li>|<li><a href="|">|</a></li>|')
{
  $pid = intval($pid);
  $sid = intval($sid);

  $tmp = '';
  $arr = explode('|', $code);
  $res = $GLOBALS['db']->getAll("SELECT * FROM channel WHERE id = " . $pid);

  foreach ($res as $row) {
    $tmp = $arr[5] . ($row['id'] == $sid ? $arr[0] : $arr[2]) . c_url($row['id'], $row['c_link']) . $arr[3] . $row['c_name'] . $arr[4];

    $tmp = $row['c_parent'] ? current_channel_location($row['c_parent'], $sid, $code) . $tmp : $tmp;
  }
  return $tmp;
}

/*
 * -------------------------
 * check
 * -------------------------
*/
// 密码hash
function psw_hash($str)
{
  return function_exists('password_hash')
    ? password_hash(str_text($str), PASSWORD_DEFAULT)
    : md5(str_text($str));
}
// 效验密码hash
function psw_verify($str, $hash)
{
  return function_exists('password_hash')
    ? password_verify(str_text($str), $hash)
    : psw_hash($str) == $hash;
}
// 身份证效验码效验
function checkIdCard($idCard)
{
  $Wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);    // 加权因子
  $ValideCode = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', 2);        // 身份证验证位值.10代表X
  $sum = '';
  for ($i = 0; $i < 17; $i++) {
    $sum += $Wi[$i] * $idCard[$i];            // 加权求和
  }
  $valCodePosition = $sum % 11;
  return $ValideCode[$valCodePosition];
}
// 使用正则验证(数据, 规则)
function regex($data, $rule)
{
  $validate = array(
    'require'   =>  '/\S+/',
    'email'     =>  '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
    'mobile'     =>  '/^1[3456789]{1}\d{9}$/',
    'cnid'     =>  '/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/',
    'url'       =>  '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
    'date'      =>  '/^\d+(\/|\-|\.)\d+(\/|\-|\.)\d+',
    'currency'  =>  '/^\d+(\.\d+)?$/',
    'number'    =>  '/^\d+$/',
    'zip'       =>  '/^\d{6}$/',
    'integer'   =>  '/^[-\+]?\d+$/',
    'double'    =>  '/^[-\+]?\d+(\.\d+)?$/',
    'english'   =>  '/^[A-Za-z]+$/',
    'strong_password' => '/^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,16}$/',
  );
  // 检查是否有内置的正则表达式
  if (isset($validate[strtolower($rule)])) {
    $rule = $validate[strtolower($rule)];
  }
  return preg_match($rule, $data) === 1;
}
// 验证数据 支持 in between length regex expire
// expire min <= $value <= max
function check($value, $type = '', $rule = '')
{
  $type = strtolower(trim($type));
  switch ($type) {
    case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
    case 'notin':
      $range = explode(',', $rule);
      return $type == 'in' ? in_array($value, $range) : !in_array($value, $range);
    case 'between': // 验证是否在某个范围
    case 'notbetween': // 验证是否不在某个范围
      list($min, $max) = explode(',', $rule);
      return $type == 'between' ? $value >= $min && $value <= $max : $value < $min || $value > $max;
    case 'length': // 验证长度
      $length = mb_strlen($value, 'utf-8'); // 当前数据长度
      if (strpos($rule, ',')) { // 长度区间
        list($min, $max) = explode(',', $rule);
        return $length >= $min && $length <= $max;
      }
      // 指定长度
      return $length == $rule;
    case 'expire':
      list($start, $end) = explode(',', $rule);
      if (!is_numeric($start)) {
        $start = local_strtotime($start);
      }
      if (!is_numeric($end)) {
        $end = local_strtotime($end);
      }
      return gmtime() >= $start && gmtime() <= $end;
    case 'email':
      return preg_match("/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i", $value) !== false ? true : false;
    case 'verifycode':
      $verifycode = $_SESSION[$rule];
      $value = is_numeric($value) ? intval($value) : strtolower($value);
      return $value == $verifycode;
    case 'idcode':
      return checkIdCard($value) == substr($value, -1);
    case 'regex':
    default:    // 默认使用正则验证 可以使用验证类中定义的验证名称
      // 检查附加规则
      return regex($value, $rule);
  }
}



// 比对数组数据更新
function set_array_update($arr_prev, $arr)
{
  foreach ($arr_prev as $key => $val) {
    if (!array_key_exists($key, $arr)) {
      $arr[$key] = $arr_prev[$key];
    }
    if ($arr_prev[$key] != $arr[$key]) {
      $arr_prev[$key] = $arr[$key];
    }
  }
  return $arr_prev;
}
// 判断移动端
function is_mobile()
{
  $regExp = '/nokia|iphone|android|samsung|htc|motorola|blackberry|ericsson|huawei|dopod|amoi|gionee|^sie\\-|^bird|^zte\\-|haier|';
  $regExp .= 'blazer|netfront|helio|hosin|novarra|techfaith|palmsource|^mot\\-|softbank|foma|docomo|kddi|up\\.browser|up\\.link|';
  $regExp .= 'symbian|smartphone|midp|wap|phone|windows ce|CoolPad|webos|iemobile|^spice|longcos|pantech|portalmmm|';
  $regExp .= 'alcatel|ktouch|nexian|^sam\\-|s[cg]h|^lge|philips|sagem|wellcom|bunjalloo|maui|';
  $regExp .= 'jig\\s browser|hiptop|ucweb|ucmobile|opera\\s*mobi|opera\\*mini|mqqbrowser|^benq|^lct';
  $regExp .= '480×640|640x480|320x320|240x320|320x240|176x220|220x176/i';

  return !isset($_SERVER['HTTP_USER_AGENT']) ? true : @$_GET['mobile'] || isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']) || preg_match($regExp, strtolower($_SERVER['HTTP_USER_AGENT']));
}
function is_wechat_qrcode()
{
  return (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false);
}
function is_alipay_qrcode()
{
  return (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false);
}

function is_admin()
{
  return 'admino' == $_GET['s'] || 'admin' == $_GET['s'];
}
function is_user()
{
  return 'user' == $_GET['s'];
}
function is_home()
{
  return $_GET['m'] == 'index' && ($_GET['c'] == 'index' || null === $_GET['c']);
}
function is_search()
{
  return $_GET['c'] == 'search';
}
function is_channel()
{
  return $_GET['c'] == 'channel';
}
function is_detail()
{
  return $_GET['c'] == 'detail';
}
function check_browser()
{
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8.0') || strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7.0') || strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.0')) {
    return false;
  }
  return true;
}
function check_domain($str)
{
  if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
    $arr = explode(':', $_SERVER['HTTP_HOST']);
    $res = $arr[0];
  } else {
    $res = $_SERVER['HTTP_HOST'];
  }

  return strpos($str, $res) !== false ? true : false;
}

/*
 * -------------------------
 * etc
 * -------------------------
*/
// 替换语言文件内的[]参数
// $p 参数名 $v 参数值 $s 替换字串
function trans_p($p, $v, $s, $t = 'array')
{
  if ($t == 'array') {
    $res = $s;
    foreach ($p as $key => $val) {
      $res = str_replace($p[$key], $v[$key], $res);
    }
  } else {
    $res = str_replace($p, $v, $s);
  }
  return $res;
}

// 多维数组转单维
// array(array("0"=>值),array("0"=>值)，...)
// array("0"=>值,"1"=>值,...)
function get_easy_array($many_arr, $many_key)
{
  $res = array();
  foreach ($many_arr as $val) {
    $res[] = $val[$many_key];
  }
  return $res;
}
// 二维数组排列组合
function get_array_pc($array, $res = array(), $n = 0, $size = 1)
{
  $res = array();
  $size = count($array);
  // 只有一种属性
  if ($size == 1 && $n == 0) {
    return $array[0];
  }

  while ($size) {
    $arr1 = array_shift($array);
    $size--;
    if ($size && $n == 0) {
      $arr2 = array_shift($array);
      $size--;
    } else {
      $arr2 = $res;
      $res = array();
    }

    foreach ($arr1 as $val) {
      foreach ($arr2 as $v) {
        $res[] = $val . ',' . $v;
      }
    }

    $n++;
  }

  return $res;
}
function array_have($arr, $key, $val, $returnKey = '')
{
  if (!is_array($arr)) {
    return false;
  }

  foreach ($arr as $row) {
    if ($val == $row[$key]) {
      return $returnKey ? $row[$returnKey] : $row[$key];
    }
  }

  return false;
}
// 数组按值排序
function array_sort($arr, $key, $sort = '0')
{
  $res = array_column($arr, $key);
  if ($sort) {
    array_multisort($res, SORT_DESC, $arr);
  } else {
    array_multisort($res, SORT_ASC, $arr);
  }
  return $arr;
}
function hook($hook, $params = NULL)
{
  Hook::listen($hook, $params);
}
//smtp邮件发送
function smtp_mail($mailto, $subject, $body, $system = 0)
{
  $smtpserver = SMTP_SERVER;
  //SMTP服务器
  $smtpserverport = 25;
  //SMTP服务器端口
  $smtpusermail = SMTP_EMAIL;
  //SMTP服务器的用户邮箱
  $smtpemailto = $mailto;
  //发送给谁
  $smtpuser = SMTP_ID;
  //SMTP服务器的用户帐号
  $smtppass = SMTP_PASS;
  //SMTP服务器的用户密码
  // $mailsubject = $subject;
  $mailsubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
  //邮件主题
  $mailbody = $body;
  if ($system) {
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=utf-8" . "\r\n";

    // 更多报头
    $headers .= 'From: <' . SMTP_EMAIL . '>' . "\r\n";
    return mail($smtpemailto, $mailsubject, $mailbody, $headers);
  } else {
    $smtp = new Smtp($smtpserver, $smtpserverport, $smtpuser, $smtppass);
    $smtp->debug = false;
    return $smtp->smtp_mail($smtpemailto, $smtpusermail, $mailsubject, $mailbody);
  }
}

/*
 * -------------------------
 * js
 * -------------------------
*/
function alert($msg)
{
  echo '<script type="text/javascript">alert("' . $msg . '");</script>';
}
function alert_back($msg)
{
  die('<script type="text/javascript">alert("' . $msg . '");window.history.back();</script>');
}
//提示后跳转
function alert_href($msg, $url)
{
  die('<script type="text/javascript">alert("' . $msg . '");window.location.href="' . $url . '"</script>');
}
function back()
{
  die('<script type="text/javascript">window.history.back();</script>');
}
function url_back($msg = '')
{
  if (empty(get_url_back())) {
    if (!empty($msg)) {
      alert_href($msg, './');
    }
    href('./');
  }

  if (!empty($msg)) {
    alert_href($msg, get_url_back());
  }

  href(get_url_back());
}
function href($url)
{
  die('<script type="text/javascript">window.location.href="' . $url . '"</script>');
}
function admin_href($var = '')
{
  $str = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '/') + 1);
  if (substr_count($str, '_') > 1) {
    list($pre, $main) = explode('_', $str);
    $url = $pre . '_' . $main . '.php' . (isset($_GET['cid']) ? '?cid=' . $_GET['cid'] : '');
    $var ? alert_href($var, $url) : href($url);
  } else {
    $url = $str . (isset($_GET['cid']) ? '?cid=' . $_GET['cid'] : '');
    $var ? alert_href($var, $url) :  href($url);
  }
}
//空值返回
function null_back($var, $url)
{
  if ($var == '' || $var === 0 || $var === '0' || $var === null) {
    alert_back($url);
  }
}
function n_back($var, $url)
{
  if ($var == '' || $var === null) {
    alert_back($url);
  }
}
//非数字返回
function non_numeric_back($var, $url)
{
  if (!is_numeric($var)) {
    alert_back($url);
  }
}
function non_numeric_href($var, $msg, $url)
{
  if (!is_numeric($var)) {
    alert_href($msg, $url);
  }
}
function equal_alert_back($var, $val, $msg)
{
  if ($var != $val) {
    alert_back($msg);
  }
  return true;
}